var tempDict = {
    diagOptions:[],
    operOptions:[]
}
$(function () {
    $('input:radio').iCheck({
        radioClass: 'iradio_square-blue',
        increaseArea: '20%'
    });

    //绑定诊断/手术上移事件
    $('#diags .fa-arrow-circle-up,#opers .fa-arrow-circle-up').die('click');
    $('#diags .fa-arrow-circle-up,#opers .fa-arrow-circle-up').live('click', function () {
        //不移动第一个主要诊断
        if ($(this).parents('.diag,.oper').prev() && !$(this).parents('.diag,.oper').prev().hasClass('main')) {
            $(this).parents('.diag,.oper').prev().before($(this).parents('.diag,.oper'));
        }
    });
    //绑定诊断/手术下移事件
    $('#diags .fa-arrow-circle-down,#opers .fa-arrow-circle-down').die('click');
    $('#diags .fa-arrow-circle-down,#opers .fa-arrow-circle-down').live('click', function () {
        if ($(this).parents('.diag,.oper').next()) {
            $(this).parents('.diag,.oper').next().after($(this).parents('.diag,.oper'));
        }
    });
    //绑定诊断/手术删除事件
    $('#diags .fa-minus-square,#opers .fa-minus-square').die('click');
    $('#diags .fa-minus-square,#opers .fa-minus-square').live('click', function () {
        //最后一个诊断/手术时不删除
        if ($(this).parents('.diag,.oper').siblings().length > 0) {
            $(this).parents('.diag,.oper').remove();
        }
    });

    //绑定输入搜索事件
    var inputLock = true;
    var keyupTimer;
    //点击选中事件
    $('.dropdown-menu').die('click keyup');
    $('.dropdown-menu').live('click','li,ol li', function(e){
        $(this).next().val($(this).find(':focus').text());
    });
    $('.dropdown-menu').live('keyup','li,ol li', function(event){
        if (event.keyCode === 13 && $(this).find(':focus').length>0) {
            $(this).next().val($(this).find(':focus').text());
        }
    });
    $('.diag input[type="text"],.oper  input[type="text"]').die('keydown compositionstart compositionend keyup input paste');
    $('.diag  input[type="text"],.oper  input[type="text"]').live('keydown', function(event) {

        var $input = $(this);

        var $dropdownMenu = $(this).prev();
        // 当提示层显示时才对键盘事件处理
        if (!$dropdownMenu.is(':visible')) {
            return;
        }
        if (event.keyCode === 40) { // 如果按的是向下方向键
            if (!$dropdownMenu.find(':focus').length) {
                // 如果提示列表没有一个被选中,则将列表第一个选中
                $dropdownMenu.find(':first').find('a').trigger('focus');
            } else {
                // 选中下一行
                $dropdownMenu.find(':focus').next().trigger('focus');
            }
        } else if (event.keyCode === 38) { // 如果按的是向上方向键
            if (!$dropdownMenu.find(':focus').length) {
                $dropdownMenu.find(':last').trigger('focus');
            } else {
                // 选中前一行
                $dropdownMenu.find(':focus').prev().trigger('focus');
            }
        } else if (event.keyCode === 13 && $dropdownMenu.find(':focus').length>0) {
            console.log($dropdownMenu.find(':focus>a').text());
            $input.val($dropdownMenu.find(':focus>a').text());
        }
    }).live('compositionstart', function(event) {
        // 中文输入开始，锁定
        // console.log('compositionstart');
        inputLock = true;
    }).live('compositionend', function(event) {
        // 中文输入结束，解除锁定
        // console.log('compositionend');
        inputLock = false;
    }).live('keyup input paste', function(event) {
        var $input = $(this);
        var $dropdownMenu = $(this).prev();
        var type = $input.data('type');
        var word;

        // 如果弹起的键是回车、向上或向下方向键则返回
        if (~$.inArray(event.keyCode, [13, 38, 40])) {
            $input.val($input.val()); // 让鼠标输入跳到最后
            return;
        }

        clearTimeout(keyupTimer);
        keyupTimer = setTimeout(function() {
            // console.log('input keyup', event);

            // 锁定状态，返回
            if (inputLock) {
                return;
            }

            word = $input.val();

            // 是否允许空数据查询
            if (!word.length) {
                $dropdownMenu.html('');
                return;
            }

            loadSuggest(type, word, $dropdownMenu);
        }, 300);
    });
});

//添加诊断或手术
function addFormRow(type) {
    var item = '<div class="'+type+'">\n' +
        // '                <div class="col-sm-6">\n' +
        // '                    <div class="form-group">\n' +
        // '                        <div class="col-sm-8 col-sm-offset-4">\n' +
        // '                            <input type="input" class="form-control code" placeholder="请输入编码">\n' +
        // '                        </div>\n' +
        // '                    </div>\n' +
        // '                </div>\n' +
        '                <div class="col-sm-12">\n' +
        '                    <div class="form-group">\n' +
        '                        <div class="col-sm-8 col-sm-offset-2">' +
        '                            <ul class="dropdown-menu dropdown-menu-left '+type+'Options" role="menu"></ul>\n' +
        '                            <input type="text" class="form-control dropdown-toggle name" data-type="'+type+'" data-toggle="dropdown" placeholder="请输入描述">' +
        '                        </div>\n' +
        '                        <div class="col-sm-2" style="padding: 5px 0 0 0;">\n' +
        '                            <i title="向上" class="fa fa-arrow-circle-up"></i>\n' +
        '                            <i title="向下" class="fa fa-arrow-circle-down"></i>\n' +
        '                            <i title="删除" class="fa fa-minus-square"></i>\n' +
        '                        </div>\n' +
        '                    </div>\n' +
        '                </div>\n' +
        '            </div>';

    $('#' + type+'s').append(item);
}

function searchGroupResult() {
    var isBlank = false;
    //验证表单
    $.each($('input[required="required"]'), function (i, n) {
        if ($(n).val() == '') {
            setTimeout(function () {
                $(n).removeClass('ue-shake');
            }, 900)
            $(n).addClass('ue-shake');
            isBlank = true;
        }
    });
    if (isBlank) return;
    $('#resultPanel .panel-body').html('<i class="fa fa-cog fa-spin fa-4x fa-fw margin-bottom text-success"></i>');

    var patient = buildPatient();
console.log(patient)
    $('#groupBtn').attr('disabled', 'disabled');
    $.post('http://10.160.12.193:8080/drgpre/service/hisCasePreGroup', JSON.stringify(patient),function(data) {
        //判断是否有错
        if (data.state === 'error') {
            drgUI.error(data.errorLog);
            $('#groupBtn').removeAttr('disabled');
            return;
        }
        $('#groupBtn').removeAttr('disabled');

        var columns = [
            {
                data: 'desc',
                title: 'DRG代码及描述',
                render: function (obj, type, full) {
                    return full.drgCode+'-'+full.drgDesc;
                }
            },
            {data: 'weight', title: '权重'},
            {data: 'avgDay', title: '平均住院日'},
            {data: 'avgFee', title: '次均费用'},
            {data: 'medCost', title: '例均医疗费用'},
            {data: 'nursCost', title: '例均护理费用'},
            {data: 'manageCost', title: '例均管理费用'},
            {data: 'techCost', title: '例均医技费用'},
            {data: 'drugCost', title: '例均药品耗材费用'},
            {data: 'riskLevel', title: '死亡风险等级'}
        ];
        var paramsDataTables = {order: [], columnDefs: [{"orderable": false, "targets": [0]}]};
        $('#resultTable').drgsDataTable(columns, data.result, paramsDataTables);
    });
}

function buildPatient() {
    var patient = {};
    var diags = [];
    var opers = [];
    $('.form-wrapper .form-control[id]').each(function (i, n) {
        if (n.value != '') {
            patient[n.id] = n.value;
        }
    })
    patient['GENDER'] = $('div.checked input.gender').val();//性别

    //诊断
    $('#diags .diag').each(function () {
        if ($(this).find('.name').val() != '') {
            diags.push($(this).find('.name').val());
        }
    })
    //手术
    $('#opers .oper').each(function () {
        if ($(this).find('.name').val() != '') {
            diags.push($(this).find('.name').val());
        }
    });
    patient['CLINIC_DIAG'] = diags;
    patient['CLINIC_OPER'] = opers;

    return patient;
}

//加载建议诊断或手术
function loadSuggest(type, keyword, $dropdownMenu){
    $dropdownMenu.html('<li><a href="#">搜索中...</a></li>');

    if (tempDict[type+'Options'].length===0){
        //字段数据未加载完，请求数据库查询
        var url;
        if (type==='diag'){
            url = contextPath + '/ICD/findDiags.dhc';
        } else {
            url = contextPath + '/ICD/findOpers.dhc';
        }
        $.post(url, {condition:keyword}, function(data) {
            $dropdownMenu.html('');
            if (data) {
                //tempDict[type+'Options'] = data;
                data.forEach(function(item){
                    $dropdownMenu.append('<li><a href="#">'+item[type+'Desc']+'</a></li>');
                })
            }
        });
    } else {
        //字典加载完后用本地字典数据过滤
        $dropdownMenu.html('');
        var list = tempDict[type+'Options'].filter(function(v){
            return v[type+'Desc'].indexOf(keyword)>-1 || v[type+'Code'].indexOf(keyword)>-1;
        });
        list.forEach(function(item){
            $dropdownMenu.append('<li><a href="#">'+item[type+'Desc']+'</a></li>');
        });
    }
}